package com.example.demo.entryWarehouse.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.demo.common.ResponseData;
import com.example.demo.entryWarehouse.dto.Acceptance;
import com.example.demo.entryWarehouse.dto.exportGoods;
import com.example.demo.entryWarehouse.entity.*;
import com.example.demo.entryWarehouse.mapper.AcceptGoodsMapper;
import com.example.demo.entryWarehouse.mapper.AcceptInformMapper;
import com.example.demo.entryWarehouse.mapper.EntryFormMapper;
import com.example.demo.entryWarehouse.mapper.StoreInformMapper;
import com.example.demo.entryWarehouse.service.AcceptInformService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.entryWarehouse.util.TestFileUtil;
import com.sun.xml.bind.v2.model.core.ID;
import org.apache.velocity.runtime.directive.Foreach;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wangxuan
 * @since 2021-05-03
 */
@Service
public class AcceptInformServiceImpl extends ServiceImpl<AcceptInformMapper, AcceptInform> implements AcceptInformService {

    @Autowired
    private AcceptInformMapper acceptInformMapper;

    @Autowired
    private StoreInformMapper storeInformMapper;

    @Autowired
    private EntryFormMapper entryFormMapper;

    @Autowired
    private AcceptGoodsMapper acceptGoodsMapper;

    @Override
    public ResponseData selectAll() {
        QueryWrapper<AcceptInform> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("id");
        List<AcceptInform> acceptInformList = acceptInformMapper.selectList(wrapper);
        return ResponseData.buildOk(acceptInformList);
    }

    @Override
    public ResponseData selectByNot() {
        QueryWrapper<AcceptInform> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("id")
                .eq("status","验收中");
        List<AcceptInform> acceptInformList = acceptInformMapper.selectList(wrapper);
        return ResponseData.buildOk(acceptInformList);
    }

    @Override
    public ResponseData selectById(String acceptId) {
        QueryWrapper<AcceptInform> wrapper = new QueryWrapper<>();
        wrapper.eq("accept_id",acceptId);
        AcceptInform acceptInform = acceptInformMapper.selectOne(wrapper);
        return ResponseData.buildOk(acceptInform);
    }

    @Override
    public ResponseData selectByStatus(String status) {
        HashMap<String,Object> map = new HashMap<>();
        map.put("status",(Object) status);
        List<AcceptInform> acceptInformList = acceptInformMapper.selectByMap(map);
        return ResponseData.buildOk(acceptInformList);
    }

    @Override
    public ResponseData addAccept(Acceptance acceptance) {
        String firstdate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMM")) + "01000000";
        String nowdate = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        QueryWrapper<AcceptInform> wrapper = new QueryWrapper<>();
        wrapper.between("createtime",(Object) firstdate,(Object)nowdate);
        Integer num = acceptInformMapper.selectCount(wrapper);
        //System.out.println(num);
        String acceptid = LocalDate.now().getYear() + "-" +LocalDate.now().getMonthValue();
        System.out.println(acceptid);
        if (num == 0){
            acceptid= acceptid +"-1";
        }else{
            acceptid = acceptid + "-" + Integer.toString(num+1);
        }

        AcceptInform acceptInform = new AcceptInform();
        acceptInform.setAcceptId(acceptid);
        acceptInform.setDepartment(acceptance.getDepartment());
        acceptInform.setProvider(acceptance.getProvider());
        acceptInform.setPlace(acceptance.getPlace());
        acceptInform.setInvoice(acceptance.getInvoice());
        acceptInform.setStatus("验收中");
        acceptInform.setCreatetime(LocalDateTime.now());
        int i = acceptInformMapper.insert(acceptInform);
        if (i > 0) return ResponseData.buildOk();
        return ResponseData.buildError();
    }

    @Override
    public ResponseData editAccept(AcceptInform acceptInform) {
        int i = acceptInformMapper.updateById(acceptInform);
        if (i > 0) return ResponseData.buildOk();
        return ResponseData.buildError();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseData editStatus(AcceptInform acceptInform) {
        List<AcceptGoods> acceptGoodsList = new ArrayList<>();
        QueryWrapper<AcceptGoods> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("accept_id",acceptInform.getAcceptId());
        acceptGoodsList = acceptGoodsMapper.selectList(wrapper1);

        //更新状态前校验此次验收的数据是否填写完整
        if (acceptGoodsList == null){
            return ResponseData.buildError("还未验收物品");
        }else {
            for (AcceptGoods ac :acceptGoodsList){
                if (ac.getName() == null || ac.getSpecification()== null || ac.getUnit()== null ||
                        ac.getType() == null|| ac.getBillNum() == null|| ac.getPrice() == null
                        || ac.getTax() == null|| ac.getYesNum()== null || ac.getNoNum() == null
                        || ac.getPosition()== null){
                    return ResponseData.buildError("验收的物品信息不完整,请完善");
                }
            }
        }

        //更新状态
        UpdateWrapper<AcceptInform> wrapper = new UpdateWrapper<>();
        wrapper.eq("accept_id",(Object) acceptInform.getAcceptId()).set("status","完成");
//      AcceptInform acceptInform1 = new AcceptInform();
//      acceptInform1.setStatus("完成");
        int i = acceptInformMapper.update(null,wrapper);

        //更新入库验收物品表的多余和短少数量

        int j= 0;
        for (AcceptGoods ac :acceptGoodsList){
            if (ac.getBillNum() == ac.getYesNum()){
                UpdateWrapper<AcceptGoods> wrapper2 = new UpdateWrapper<>();
                wrapper2.eq("accept_id",ac.getAcceptId())
                        .eq("name",ac.getName())
                        .eq("specification",ac.getSpecification())
                        .eq("unit",ac.getUnit())
                        .set("shortage",0)
                        .set("surplus",0);
                j =  acceptGoodsMapper.update(null,wrapper2);
            }else if (ac.getBillNum() > ac.getYesNum()){
                UpdateWrapper<AcceptGoods> wrapper2 = new UpdateWrapper<>();
                wrapper2.eq("accept_id",ac.getAcceptId())
                        .eq("name",ac.getName())
                        .eq("specification",ac.getSpecification())
                        .eq("unit",ac.getUnit())
                        .set("shortage",ac.getBillNum()-ac.getYesNum())
                        .set("surplus",0);
                j =  acceptGoodsMapper.update(null,wrapper2);

            }else {
                UpdateWrapper<AcceptGoods> wrapper2 = new UpdateWrapper<>();
                wrapper2.eq("accept_id",ac.getAcceptId())
                        .eq("name",ac.getName())
                        .eq("specification",ac.getSpecification())
                        .eq("unit",ac.getUnit())
                        .set("shortage",0)
                        .set("surplus",ac.getYesNum()-ac.getBillNum());
                j =  acceptGoodsMapper.update(null,wrapper2);
            }
        }

        //入库登记表数据加入
        int k = 0;
        for (AcceptGoods ac :acceptGoodsList){
            EntryForm entryForm = new EntryForm();
            entryForm.setAcceptId(ac.getAcceptId());
            entryForm.setName(ac.getName());
            entryForm.setSpecification(ac.getSpecification());
            entryForm.setUnit(ac.getUnit());
            entryForm.setPosition(ac.getPosition());
            entryForm.setPrice(ac.getPrice());
            entryForm.setEntryNum(ac.getYesNum());
            entryForm.setEntryDate(LocalDateTime.now());
//            entryForm.setKeeper();
//            entryForm.setRemark();
            k = entryFormMapper.insert(entryForm);
        }

        //库存信息表维护
        int l=0;
        for (AcceptGoods ac :acceptGoodsList){
            QueryWrapper<StoreInform> wrapper3 = new QueryWrapper<>();
            wrapper3.eq("name",ac.getName())
                    .eq("specification",ac.getSpecification())
                    .eq("unit",ac.getUnit())
                    .eq("type",ac.getType());
            StoreInform storeInform = new StoreInform();
            storeInform = storeInformMapper.selectOne(wrapper3);
            if (storeInform == null){
                StoreInform storeInform1 = new StoreInform();
                storeInform1.setName(ac.getName());
                storeInform1.setSpecification(ac.getSpecification());
                storeInform1.setUnit(ac.getUnit());
                storeInform1.setType(ac.getType());
                storeInform1.setStoreNum(ac.getYesNum());
                storeInform1.setPosition(ac.getPosition());
                l = storeInformMapper.insert(storeInform1);
            }else{
                UpdateWrapper<StoreInform> wrapper4 = new UpdateWrapper<>();
                wrapper4.eq("name",storeInform.getName())
                        .eq("specification",storeInform.getSpecification())
                        .eq("unit",storeInform.getUnit())
                        .eq("type",storeInform.getType())
                        .set("store_num",storeInform.getStoreNum()+ ac.getYesNum());
                l = storeInformMapper.update(null,wrapper4);
            }
        }


        if (i > 0 && j >0 && k >0 && l >0 ) return ResponseData.buildOk();
        return ResponseData.buildError();
    }

    @Override
    public ResponseData selectByOk() {
        QueryWrapper<AcceptInform> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("id")
                .eq("status","完成");
        List<AcceptInform> acceptInformList = acceptInformMapper.selectList(wrapper);
        return ResponseData.buildOk(acceptInformList);
    }

    //accept1.0
    @Override
    public ResponseData exportAccept(String acceptId) {
        String accepttemplate =
                TestFileUtil.getPath() + "exceltemplate" + File.separator + "accepttemplate.xlsx";
        String fileName = "物资验收记录表" + acceptId + "---" + System.currentTimeMillis() + ".xlsx";
        ExcelWriter excelWriter = EasyExcel.write(fileName).withTemplate(accepttemplate).build();
        WriteSheet writeSheet = EasyExcel.writerSheet().build();
        FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();

        QueryWrapper<AcceptInform> wrapper = new QueryWrapper<>();
        wrapper.eq("accept_id",acceptId);
        AcceptInform acceptInform = acceptInformMapper.selectOne(wrapper);
        QueryWrapper<AcceptGoods> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("accept_id",acceptId);
        List<AcceptGoods> acceptGoodsList = acceptGoodsMapper.selectList(wrapper1);
        List<exportGoods> exportGoodsList = new ArrayList<>();

        int id = 1;
        for (AcceptGoods ag: acceptGoodsList) {
            exportGoods eg = new exportGoods();
            eg.setId(id);
            id = id + 1 ;
            eg.setAcceptId(ag.getAcceptId());
            eg.setName(ag.getName());
            eg.setSpecification(ag.getSpecification());
            eg.setUnit(ag.getUnit());
            eg.setPrice(ag.getPrice());
            eg.setBillNum(ag.getBillNum());
            //计算各类物资金额
            eg.setYesNum(ag.getYesNum());
            eg.setMoney1(ag.getPrice().multiply(BigDecimal.valueOf((int)ag.getYesNum())));
            eg.setNoNum(ag.getNoNum());
            eg.setMoney2(ag.getPrice().multiply(BigDecimal.valueOf((int)ag.getNoNum())));
            eg.setShortage(ag.getShortage());
            eg.setMoney3(ag.getPrice().multiply(BigDecimal.valueOf((int)ag.getShortage())));
            eg.setSurplus(ag.getSurplus());
            eg.setMoney4(ag.getPrice().multiply(BigDecimal.valueOf((int)ag.getSurplus())));

            if (ag.getRemark() == null){
                eg.setRemark(" ");
            }else {
                eg.setRemark(ag.getRemark());
            }
            exportGoodsList.add(eg);
        }

        //求合计金额
        BigDecimal total1 = new BigDecimal(0);
        BigDecimal total2 = new BigDecimal(0);
        BigDecimal total3 = new BigDecimal(0);
        BigDecimal total4 = new BigDecimal(0);
        for (exportGoods ex: exportGoodsList) {
            total1= total1.add(ex.getMoney1());
            total2= total2.add(ex.getMoney2());
            total3= total3.add(ex.getMoney3());
            total4= total4.add(ex.getMoney4());
        }

        excelWriter.fill( exportGoodsList , fillConfig, writeSheet);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("department", acceptInform.getDepartment());
        map.put("acceptId", acceptInform.getAcceptId());
        map.put("provider", acceptInform.getProvider());
        map.put("place", acceptInform.getPlace());
        map.put("invoice", acceptInform.getInvoice());
        map.put("total1", total1);
        map.put("total2", total2);
        map.put("total3", total3);
        map.put("total4", total4);
        excelWriter.fill(map, writeSheet);
        excelWriter.finish();
        return ResponseData.buildOk();
    }

    @Override
    public void exportAccept1(HttpServletResponse response, String acceptId) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");

        String accepttemplate =
                TestFileUtil.getPath() + "exceltemplate" + File.separator + "accepttemplate.xlsx";
        String fileName = "物资验收记录表" + acceptId + "---" + System.currentTimeMillis() + ".xlsx";
        ExcelWriter excelWriter = EasyExcel.write(fileName).withTemplate(accepttemplate).build();
        WriteSheet writeSheet = EasyExcel.writerSheet().build();
        FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();

        QueryWrapper<AcceptInform> wrapper = new QueryWrapper<>();
        wrapper.eq("accept_id",acceptId);
        AcceptInform acceptInform = acceptInformMapper.selectOne(wrapper);
        QueryWrapper<AcceptGoods> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("accept_id",acceptId);
        List<AcceptGoods> acceptGoodsList = acceptGoodsMapper.selectList(wrapper1);
        List<exportGoods> exportGoodsList = new ArrayList<>();

        int id = 1;
        for (AcceptGoods ag: acceptGoodsList) {
            exportGoods eg = new exportGoods();
            eg.setId(id);
            id = id + 1 ;
            eg.setAcceptId(ag.getAcceptId());
            eg.setName(ag.getName());
            eg.setSpecification(ag.getSpecification());
            eg.setUnit(ag.getUnit());
            eg.setPrice(ag.getPrice());
            eg.setBillNum(ag.getBillNum());
            //计算各类物资金额
            eg.setYesNum(ag.getYesNum());
            eg.setMoney1(ag.getPrice().multiply(BigDecimal.valueOf((int)ag.getYesNum())));
            eg.setNoNum(ag.getNoNum());
            eg.setMoney2(ag.getPrice().multiply(BigDecimal.valueOf((int)ag.getNoNum())));
            eg.setShortage(ag.getShortage());
            eg.setMoney3(ag.getPrice().multiply(BigDecimal.valueOf((int)ag.getShortage())));
            eg.setSurplus(ag.getSurplus());
            eg.setMoney4(ag.getPrice().multiply(BigDecimal.valueOf((int)ag.getSurplus())));

            if (ag.getRemark() == null){
                eg.setRemark(" ");
            }else {
                eg.setRemark(ag.getRemark());
            }
            exportGoodsList.add(eg);
        }

        //求合计金额
        BigDecimal total1 = new BigDecimal(0);
        BigDecimal total2 = new BigDecimal(0);
        BigDecimal total3 = new BigDecimal(0);
        BigDecimal total4 = new BigDecimal(0);
        for (exportGoods ex: exportGoodsList) {
            total1= total1.add(ex.getMoney1());
            total2= total2.add(ex.getMoney2());
            total3= total3.add(ex.getMoney3());
            total4= total4.add(ex.getMoney4());
        }

        excelWriter.fill( exportGoodsList , fillConfig, writeSheet);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("department", acceptInform.getDepartment());
        map.put("acceptId", acceptInform.getAcceptId());
        map.put("provider", acceptInform.getProvider());
        map.put("place", acceptInform.getPlace());
        map.put("invoice", acceptInform.getInvoice());
        map.put("total1", total1);
        map.put("total2", total2);
        map.put("total3", total3);
        map.put("total4", total4);
        excelWriter.fill(map, writeSheet);
        excelWriter.finish();
       // return ResponseData.buildOk();
    }


    @Override
    public ResponseData exportReceive(String acceptId) {
        String receivetemplate =
                TestFileUtil.getPath() + "exceltemplate" + File.separator + "receivetemplate.xlsx";
        String fileName = "物资收料单" + acceptId + "---" + System.currentTimeMillis() + ".xlsx";
        ExcelWriter excelWriter = EasyExcel.write(fileName).withTemplate(receivetemplate).build();
        WriteSheet writeSheet = EasyExcel.writerSheet().build();
        FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();

        QueryWrapper<AcceptInform> wrapper = new QueryWrapper<>();
        wrapper.eq("accept_id",acceptId);
        AcceptInform acceptInform = acceptInformMapper.selectOne(wrapper);
        QueryWrapper<AcceptGoods> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("accept_id",acceptId);
        List<AcceptGoods> acceptGoodsList = acceptGoodsMapper.selectList(wrapper1);
        List<exportGoods> exportGoodsList = new ArrayList<>();

        int id = 1;
        for (AcceptGoods ag: acceptGoodsList) {
            exportGoods eg = new exportGoods();
            eg.setId(id);
            id = id + 1 ;
            eg.setAcceptId(ag.getAcceptId());
            eg.setName(ag.getName());
            eg.setSpecification(ag.getSpecification());
            eg.setUnit(ag.getUnit());
            eg.setPrice(ag.getPrice());
            eg.setBillNum(ag.getBillNum());
            //计算各类物资金额
            eg.setYesNum(ag.getYesNum());
            eg.setMoney1(ag.getPrice().multiply(BigDecimal.valueOf((int)ag.getYesNum())));
            eg.setTax(ag.getTax());
            eg.setMoney2(ag.getPrice().multiply(BigDecimal.valueOf((int)ag.getYesNum())).multiply(ag.getTax()));
            eg.setRemark(" ");
            exportGoodsList.add(eg);
        }

        //求合计金额
        BigDecimal total1 = new BigDecimal(0);
        BigDecimal total2 = new BigDecimal(0);
        for (exportGoods ex: exportGoodsList) {
            total1= total1.add(ex.getMoney1());
            total2= total2.add(ex.getMoney2());
        }

        excelWriter.fill( exportGoodsList , fillConfig, writeSheet);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("department", acceptInform.getDepartment());
        map.put("acceptId", acceptInform.getAcceptId());
        map.put("provider", acceptInform.getProvider());
        map.put("total1", total1);
        map.put("total2", total2);

        excelWriter.fill(map, writeSheet);

        excelWriter.finish();


        return ResponseData.buildOk(excelWriter);
    }

    @Override
    public ResponseData exportReturn(String acceptId) {
        String returntemplate =
                TestFileUtil.getPath() + "exceltemplate" + File.separator + "returntemplate.xlsx";
        String fileName = "物资退料单" + acceptId + "---" + System.currentTimeMillis() + ".xlsx";
        ExcelWriter excelWriter = EasyExcel.write(fileName).withTemplate(returntemplate).build();
        WriteSheet writeSheet = EasyExcel.writerSheet().build();
        FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();

        QueryWrapper<AcceptInform> wrapper = new QueryWrapper<>();
        wrapper.eq("accept_id",acceptId);
        AcceptInform acceptInform = acceptInformMapper.selectOne(wrapper);
        QueryWrapper<AcceptGoods> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("accept_id",acceptId);
        List<AcceptGoods> acceptGoodsList = acceptGoodsMapper.selectList(wrapper1);
        List<exportGoods> exportGoodsList = new ArrayList<>();

        int id = 1;
        for (AcceptGoods ag: acceptGoodsList) {
            if(ag.getNoNum() != 0){
                exportGoods eg = new exportGoods();
                eg.setId(id);
                id = id + 1 ;
                eg.setAcceptId(ag.getAcceptId());
                eg.setName(ag.getName());
                eg.setSpecification(ag.getSpecification());
                eg.setUnit(ag.getUnit());
                eg.setPrice(ag.getPrice());
                eg.setNoNum(ag.getNoNum());
                eg.setRemark(" ");
                exportGoodsList.add(eg);
            }
        }

        excelWriter.fill( exportGoodsList , fillConfig, writeSheet);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("department", acceptInform.getDepartment());
        map.put("acceptId", acceptInform.getAcceptId());
        map.put("provider", acceptInform.getProvider());
        excelWriter.fill(map, writeSheet);
        excelWriter.finish();

        return ResponseData.buildOk();
    }
}
